package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.constant.RedisNewsConst;
import com.dongdongshop.pojo.Cart;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.pojo.TbOrderItem;
import com.dongdongshop.service.CartServiceI;
import com.dongdongshop.service.TbItemServiceI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@com.alibaba.dubbo.config.annotation.Service
public class CartServiceImpl implements CartServiceI {
    private final Logger logger = LoggerFactory.getLogger(CartServiceImpl.class);

    @Reference
    private TbItemServiceI tbItemServiceI;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public List<Cart> addToCart(List<Cart> cartList, Long itemId, Integer num) {
        //1.根据商品SKU ID查询SKU商品信息
        TbItem item = tbItemServiceI.selectItemById(itemId);
        //2.获取商家ID
        String sellerId = item.getSellerId();
        //3.根据商家ID判断购物车列表中是否存在该商家的购物车
        Cart ct = searchCartBySellerId(sellerId,cartList);

        //4.如果购物车列表中不存该商家的购物车
        if(ct == null){
            //4.1创建新购物车对象
            ct = new Cart();
            ct.setSellerId(sellerId);
            ct.setSellerName(item.getSeller());

            //将商品的SKU数据保存到订单明细对象中
            TbOrderItem orderItem = getTbOrderItem(item, num);
            List<TbOrderItem> orderItemList = new ArrayList<>();
            orderItemList.add(orderItem);
            ct.setOrderItemList(orderItemList);

            //4.2 将新建的购物车对象添加到购物车列表
            cartList.add(ct);
        }else {
            //5.如果购物车列表中存在该商品的购物车
            //查询购物车明细列表中是否存在该商品
            List<TbOrderItem> orderItemList = ct.getOrderItemList();
          /*  TbOrderItem order = null;
            for (TbOrderItem orderItem : orderItemList) {
                if(orderItem.getItemId().equals(item.getId())){
                    order = orderItem;
                    break;
                }
            }*/
            TbOrderItem tbOrderItem = searchTbOrderItemById(orderItemList, item);
            //5.1 如果没有，新增购物车明细
            if(tbOrderItem == null){
                tbOrderItem = getTbOrderItem(item,num);
                ct.getOrderItemList().add(tbOrderItem);
            }else {
                //5.2如果有，在原购物车明细上添加数量，更改金额
                tbOrderItem.setNum(tbOrderItem.getNum() + num);
                //总价格
                tbOrderItem.setTotalFee(new BigDecimal(tbOrderItem.getNum() * tbOrderItem.getPrice().doubleValue()));

                //如果数量加完只是num<=0，我们就把他移除掉，而不是继续保留在集合中
                if(tbOrderItem.getNum() <= 0){
                    ct.getOrderItemList().remove(tbOrderItem);
                }

                //如果移出后OrderItemList大小为0了，那么我们将把这个cart给移除掉
                if(ct.getOrderItemList().size() <= 0){
                    cartList.remove(ct);
                }
            }
        }

        return cartList;
    }

    public Cart searchCartBySellerId(String sellerId,List<Cart> cartList){
       /* for (Cart cart : cartList) {
            if(cart.getSellerId().equals(sellerId)){
                return cart;
            }
        }*/
        return cartList.stream().filter(x -> x.getSellerId().equals(sellerId)).findFirst().orElse(null);
    }


    //将商品的数据保存到订单对象中

    public TbOrderItem getTbOrderItem(TbItem item,Integer num){
        TbOrderItem tbOrderItem = new TbOrderItem();
        tbOrderItem.setGoodsId(item.getGoodsId());
        tbOrderItem.setTitle(item.getTitle());
        tbOrderItem.setItemId(item.getId());
        tbOrderItem.setNum(num);
        tbOrderItem.setPicPath(item.getImage());
        tbOrderItem.setPrice(item.getPrice());
        tbOrderItem.setTotalFee(new BigDecimal(item.getPrice().doubleValue() * num));//总价格 单价 * 数量
        return tbOrderItem;
    }
    //根据商品的id查询购物车明细中商品的数据

    public TbOrderItem searchTbOrderItemById(List<TbOrderItem> orderItemList,TbItem item){
        return orderItemList.stream().filter(x -> x.getItemId().equals(item.getId())).findFirst().orElse(null);
    }

    /*
    * 从redis中获取购物车信息
    * */
    @Override
    public List<Cart> findCartListFromRedis(String username) {
        logger.info("从redis中获取购物车，{}",username);
        List<Cart> cartList = (List<Cart>)redisTemplate.boundHashOps(RedisNewsConst.cartList).get(username);
        logger.info("查询成功，购物车数据为，{}",cartList);
        Optional<List<Cart>> optional = Optional.ofNullable(cartList);
        return optional.orElse(new ArrayList<>());
    }

    @Override
    public void addToCartRedis(List<Cart> cartList, String username) {
        logger.info("将购物车数据保存到redis中，{}",username);
        redisTemplate.boundHashOps(RedisNewsConst.cartList).put(username,cartList);
        logger.info("购物车数据保存redis成功!");
    }

    @Override
    public List<Cart> mergeCarList(List<Cart> cartsCookie, List<Cart> cartsRedis) {
        //遍历cookie集合
        for (Cart cart : cartsCookie) {
            List<TbOrderItem> orderItemList = cart.getOrderItemList();
            for (TbOrderItem orderItem : orderItemList) {
                cartsRedis = addToCart(cartsRedis,orderItem.getItemId(),orderItem.getNum());
            }
        }
        return cartsRedis;
    }
}
